package com.xhji.web.mvc.response;

import com.xhji.web.mvc.annotations.NoWarp;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 响应结果装饰器.
 */
@RestControllerAdvice
public interface ResponseDecorate extends ResponseBodyAdvice<Object>, EnvironmentAware {
    GenericResponse<Object> decorate(Object result, Throwable e, Method method);

    @Override
    default boolean supports(
            MethodParameter methodParameter,
            Class<? extends HttpMessageConverter<?>> clazz
    ) {
        return Objects.nonNull(AnnotationUtils.findAnnotation(methodParameter.getMethod(), RequestMapping.class)) && AnnotationUtils.findAnnotation(methodParameter.getMethod(), NoWarp.class) == null;
    }

    @Override
    default Object beforeBodyWrite(
            Object o,
            MethodParameter methodParameter,
            MediaType mediaType,
            Class<? extends HttpMessageConverter<?>> clazz,
            ServerHttpRequest serverHttpRequest,
            ServerHttpResponse serverHttpResponse
    ) {
        Class<?> returnType = methodParameter.getMethod().getReturnType();
        if (GenericResponse.class.isAssignableFrom(returnType)) {
            return o;
        }
        return this.decorate(o, null, methodParameter.getMethod());
    }

}
